package com.javaDemo.ti;

public class OldEvenTest {

    public static void main(String[] args) {
        //监视器对象
        Object monitor = new Object();
        new Thread(new EvenPrintTask(monitor), "偶数").start();
        new Thread(new OldPrintTask(monitor), "奇数").start();
    }


    static class OldPrintTask implements Runnable {

        private Object monitor;
        //奇数线程从1开始打印
        private int value = 1;

        public OldPrintTask(Object monitor) {
            this.monitor = monitor;
        }

        @Override
        public void run() {
            while (value <100) {
                synchronized (monitor) {
                    System.out.println(Thread.currentThread().getName() + ":" + value);
                    value += 2;
                    monitor.notify();
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        monitor.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    static class EvenPrintTask implements Runnable {

        private Object monitor;
        //偶数对象
        private int value = 0;

        public EvenPrintTask(Object monitor) {
            this.monitor = monitor;
        }

        @Override
        public void run() {
            while (value <= 100) {
                synchronized (monitor) {
                    System.out.println(Thread.currentThread().getName() + ":" + value);
                    value += 2;
                    monitor.notify();
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        monitor.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}

